package com.hotec.PROJECT_NAME.component.lock;


import com.hotec.PROJECT_NAME.component.basic.LockAble;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import com.hotec.PROJECT_NAME.utils.UtilsLock;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Consumer;

@Component
public class LockAndRunService {
    public void lockAndRun(String key, Runnable runnable) {
        if (UtilsLock.getLock(key)) {
            try {
                runnable.run();
            } finally {
                UtilsLock.clearLock(key);
            }
        }else{
            throw new BizException("任务正在被执行，请稍后再试");
        }
    }

    public <T extends LockAble> void lockAndRun(T data, Consumer <T>  action) {
        lockAndRun("prefix", data, action);
    }

    public <T extends LockAble> void lockAndRun(String prefix, T data, Consumer <T>  action) {
        if (UtilsLock.getLock(data.getLockKey(prefix))) {
            try {
                action.accept(data);
            } finally {
                UtilsLock.clearLock(data.getLockKey(prefix));
            }
        }else{
            throw new BizException("任务正在被执行，请稍后再试");
        }
    }

    public <T extends LockAble> void lockAndRun(List<T> data, Consumer <T>  action) {
        data.forEach(t -> lockAndRun(t,action));
    }
}
